<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use fast\Tree;
use Monolog\Handler\IFTTTHandler;
use think\Db;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\PDOException;
use think\exception\ValidateException;
use fast\Pinyin;
/**
 * 车型管理
 *
 * @icon fa fa-circle-o
 */
class Vehicle extends Backend
{

    /**
     * Vehicle模型对象
     * @var \app\admin\model\Vehicle
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Vehicle;
        $this->categorylist = $this->model
            // ->where('del', 0)
            ->where('pid', 0)
            ->order('first asc,mergename desc')
            ->select()
            ->toArray();
        $categorydata = [0 => ['type' => 'all', 'mergename' => __('顶级分类'), 'level' => __('0')]];
        $this->view->assign('flastList', $this->model->getHot());
        $this->view->assign('hierarchy', $this->model->getHierarchy());
        $this->view->assign('parentList', $categorydata);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            $search = $this->request->request("search", '');

            $type = $this->request->request("type", '');
            $id = $this->request->request("id", 0);
            if (!empty($id)) {
                $where = [];
                $where['pid'] = ['eq', $id];
                // $where['del'] = ['eq', 0];

                $categoryData = $this->model->get($id);
                
                // $categorylist = $this->model->where($where)->order('mergename desc')->select()->toArray();
                $categorylist = $this->model->where($where)->orderRaw('CONVERT(mergename USING utf8) asc')->select()->toArray();

                if ($categoryData && $categoryData['level'] == 1 || $categoryData['level'] == 2) {
                    $sort = [];
                    foreach ($categorylist as $key => $item) {
                        preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u' , $item['mergename'],$result);
                        $name = implode('',$result[0]);
                        $name = Pinyin::get($name);
                        $categorylist[$key]['first'] = $name;
                        $sort[] = $name;
                    }
                    array_multisort($sort, SORT_ASC, $categorylist);
                } else {
                    foreach ($categorylist as $key => $item) {
                        $categorylist[$key]['spacer'] = '';
                        $categorylist[$key]['haschild'] = 0;
                    }
                }
            } else {
                $categorylist = $this->categorylist;
            }

            //构造父类select列表选项数据
            $list = [];
            foreach ($categorylist as $k => $v) {
                if ($search) {
                    if ($search && strtoupper($v['first']) === strtoupper($search) || strpos($v['mergename'], $search) !== false) {
                        $list[] = $v;
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $categorylist;
                    } else {
                        $list[] = $v;
                    }
                }
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig('model_Id', $this->request->request("id", 0));
        return $this->view->fetch();
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            $ids = $this->request->param('model_Id', 0);
            $addVehile = $this->model->get($ids);
            $level = 0;
            if (!empty($addVehile)) {
                $level = $addVehile['level'];
                $this->view->assign('addVehile', $addVehile);
            }
            $this->view->assign('level', $level);
            $this->view->assign('ids', $ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $strpid = explode('.', $params['pid']);

        $params['pid'] = $strpid[0];
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $is_pid = Db::name('vehicle')->where('id', $params['pid'])->find();

        $params['pids'] = $params['pid'] == 0 ? 0 : $is_pid['pids'] . '-' . $is_pid['id'];

        if ($params['pid'] == 0) {
            $py = Pinyin::get($params['mergename']);
            $params['first'] = empty($py) ? 'Z' : strtoupper(mb_substr($py,0,1));
        }

        if ($is_pid['level'] == 5) {
            $this->error('已经最高,无法再添加子分类');
        } else {
            $params['level'] = $is_pid['level'] + 1;
        }

        if ($params['level'] != 1) {
            $params['first'] = $is_pid['first'];
            unset($params['flag']);
        }

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['create_time'] = time();

            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $addVehile = $this->model->get($row['pid']);
            $level = 0;
            if (!empty($addVehile)) {
                $level = $addVehile['level'];
                $this->view->assign('addVehile', $addVehile);
            }
            $this->view->assign('level', $level);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if ($row['pid'] == 0) {
            $py = Pinyin::get($params['mergename']);
            $params['first'] = empty($py) ? 'Z' : strtoupper(mb_substr($py,0,1));
        }
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $vehicle = Db::name('vehicle')->where('id', $ids)->find();

            if ($vehicle['pid'] == 0 && $params['first'] !== $vehicle['first']) {
                Db::name('vehicle')->where('pid', $vehicle['id'])->update(['first' => $params['first']]);
            }

            if (empty($params['first'])) {
                $params['first'] = $vehicle['first'];
            }

            if ($vehicle['pid'] != 0) {
                unset($params['first']);
                unset($params['flag']);
            }

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function del($ids = null)
    {

        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }

        $ids = $ids ?: $this->request->post("ids");

        $vehicle = $this->model::get($ids);

        if (empty($vehicle)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $count = 0;
        Db::startTrans();
        try {
            if ($vehicle['level'] == 5) {
                $vehicle->del = 1;
                $vehicle->save();
                $count = $vehicle->id;
            } else {
                $arrId = $this->model->vehidelete($ids);
                array(array_push($arrId, (int)$ids));
                $count = $this->model->where('id', 'in', $arrId)->update([
                    'del' => 1
                ]);
            }

            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    //导入
     public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
        //         dump($fieldArr);
        // die;
        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                
                foreach ($temp as $k => $v) {
                    // if (isset($fieldArr[$k]) && $k !== '') {
                        $row[] = $v;
                    // }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        // dump($insert);
        // die;
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        try {
            // insertGetId
            // //是否包含admin_id字段
            // $has_admin_id = false;
            // foreach ($fieldArr as $name => $key) {
            //     if ($key == 'admin_id') {
            //         $has_admin_id = true;
            //         break;
            //     }
            // }
            // if ($has_admin_id) {
            //     $auth = Auth::instance();
            //     foreach ($insert as &$val) {
            //         if (!isset($val['admin_id']) || empty($val['admin_id'])) {
            //             $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
            //         }
            //     }
            // }
            foreach($insert as $k=>$v){
              
            $t1 = $this->model->where("mergename",$v[0])->where("pid",0)->find();
            if(!$t1){
                //一级
                $id1 = $this->model->insertGetId([
                    "pid"=>0,
                    "level"=>1,
                    "create_time"=>time(),
                    "first"=>$v[5],
                    "mergename"=>$v[0],
                    "pids"=>0
                    ]);
                $this->model->where("id",$id1)->update(["weigh"=>$id1]);
                //二级
                $id2 = $this->model->insertGetId([
                    "pid"=>$id1,
                    "level"=>2,
                    "create_time"=>time(),
                    "first"=>$v[5],
                    "mergename"=>$v[1],
                    "pids"=>"0-".$id1
                    ]);
                $this->model->where("id",$id2)->update(["weigh"=>$id2]);
                //三级
                $id3 = $this->model->insertGetId([
                    "pid"=>$id2,
                    "level"=>3,
                    "create_time"=>time(),
                    "first"=>$v[5],
                    "mergename"=>$v[2],
                    "pids"=>"0-".$id1."-".$id2
                    ]);
                $this->model->where("id",$id3)->update(["weigh"=>$id3]);
                //四级
                $id4 = $this->model->insertGetId([
                    "pid"=>$id3,
                    "level"=>4,
                    "create_time"=>time(),
                    "first"=>$v[5],
                    "mergename"=>$v[3],
                    "pids"=>"0-".$id1."-".$id2."-".$id3
                    ]);
                $this->model->where("id",$id4)->update(["weigh"=>$id4]);
                //五级
                $id5 = $this->model->insertGetId([
                    "pid"=>$id4,
                    "level"=>4,
                    "create_time"=>time(),
                    "first"=>$v[5],
                    "mergename"=>$v[4],
                    "pids"=>"0-".$id1."-".$id2."-".$id3."-".$id4
                    ]);
                $this->model->where("id",$id5)->update(["weigh"=>$id5]);
            }else{
                $id1 = $t1["id"];
                $t2 = $this->model->where("mergename",$v[1])->where("pid",$id1)->find();
                if(!$t2){
                    //二级
                    $id2 = $this->model->insertGetId([
                        "pid"=>$id1,
                        "level"=>2,
                        "create_time"=>time(),
                        "first"=>$v[5],
                        "mergename"=>$v[1],
                        "pids"=>"0-".$id1
                        ]);
                    $this->model->where("id",$id2)->update(["weigh"=>$id2]);
                    //三级
                    $id3 = $this->model->insertGetId([
                        "pid"=>$id2,
                        "level"=>3,
                        "create_time"=>time(),
                        "first"=>$v[5],
                        "mergename"=>$v[2],
                        "pids"=>"0-".$id1."-".$id2
                        ]);
                    $this->model->where("id",$id3)->update(["weigh"=>$id3]);
                    //四级
                    $id4 = $this->model->insertGetId([
                        "pid"=>$id3,
                        "level"=>4,
                        "create_time"=>time(),
                        "first"=>$v[5],
                        "mergename"=>$v[3],
                        "pids"=>"0-".$id1."-".$id2."-".$id3
                        ]);
                    $this->model->where("id",$id4)->update(["weigh"=>$id4]);
                    //五级
                    $id5 = $this->model->insertGetId([
                        "pid"=>$id4,
                        "level"=>4,
                        "create_time"=>time(),
                        "first"=>$v[5],
                        "mergename"=>$v[4],
                        "pids"=>"0-".$id1."-".$id2."-".$id3."-".$id4
                        ]);
                    $this->model->where("id",$id5)->update(["weigh"=>$id5]);
                }else{
                    $id2 = $t2["id"];
                    $t3 = $this->model->where("mergename",$v[2])->where("pid",$id2)->find();
                    if(!$t3){
                        //三级
                        $id3 = $this->model->insertGetId([
                            "pid"=>$id2,
                            "level"=>3,
                            "create_time"=>time(),
                            "first"=>$v[5],
                            "mergename"=>$v[2],
                            "pids"=>"0-".$id1."-".$id2
                            ]);
                        $this->model->where("id",$id3)->update(["weigh"=>$id3]);
                        //四级
                        $id4 = $this->model->insertGetId([
                            "pid"=>$id3,
                            "level"=>4,
                            "create_time"=>time(),
                            "first"=>$v[5],
                            "mergename"=>$v[3],
                            "pids"=>"0-".$id1."-".$id2."-".$id3
                            ]);
                        $this->model->where("id",$id4)->update(["weigh"=>$id4]);
                        //五级
                        $id5 = $this->model->insertGetId([
                            "pid"=>$id4,
                            "level"=>4,
                            "create_time"=>time(),
                            "first"=>$v[5],
                            "mergename"=>$v[4],
                            "pids"=>"0-".$id1."-".$id2."-".$id3."-".$id4
                            ]);
                        $this->model->where("id",$id5)->update(["weigh"=>$id5]);
                    }else{
                        $id3 = $t3["id"];
                        $t4 = $this->model->where("mergename",$v[3])->where("pid",$id3)->find();
                        if(!$t4){
                            //四级
                            $id4 = $this->model->insertGetId([
                                "pid"=>$id3,
                                "level"=>4,
                                "create_time"=>time(),
                                "first"=>$v[5],
                                "mergename"=>$v[3],
                                "pids"=>"0-".$id1."-".$id2."-".$id3
                                ]);
                            $this->model->where("id",$id4)->update(["weigh"=>$id4]);
                            //五级
                            $id5 = $this->model->insertGetId([
                                "pid"=>$id4,
                                "level"=>4,
                                "create_time"=>time(),
                                "first"=>$v[5],
                                "mergename"=>$v[4],
                                "pids"=>"0-".$id1."-".$id2."-".$id3."-".$id4
                                ]);
                            $this->model->where("id",$id5)->update(["weigh"=>$id5]);
                        }else{
                            $id4 = $t4["id"];
                            $t5 = $this->model->where("mergename",$v[4])->where("pid",$id4)->find();
                            if(!$t5){
                                //五级
                                $id5 = $this->model->insertGetId([
                                    "pid"=>$id4,
                                    "level"=>4,
                                    "create_time"=>time(),
                                    "first"=>$v[5],
                                    "mergename"=>$v[4],
                                    "pids"=>"0-".$id1."-".$id2."-".$id3."-".$id4
                                    ]);
                                $this->model->where("id",$id5)->update(["weigh"=>$id5]);
                            }
                        }
                    }
                }
            }
            
        }
            // $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
